// Modal adpater for AJAX loading modal

'use strict';

// modal trigger
$(document).on('click', '[data-toggle="modal"]', function (e) {
  e.preventDefault();
  var $this = $(e.currentTarget);
  if(!$(this).data("opening")) {
    var url = $this.attr('href'),
        id = $this.attr('data-target').slice(1);
    
    $(this).data("opening", true)
    
    if (url.indexOf('#') === 0) {
      $(url).modal('show');
    } else {
      var params = $this.attr('data-form-params');
      var data = params ? $('#' + params).serialize() : {};

      $.get(url, data, function (data) {
        $('<div class="modal fade" id="' + id + '" role="dialog" aria-hidden="true">' + data + '</div>').modal().on('hidden.bs.modal', function (e) {
          return $(e.currentTarget).remove();
        }).on('shown.bs.modal', function () {
          return $this.trigger('shown.modal');
        });
      });
    }
  }
}).off('click.bs.modal.data-api');

$(document).on('shown.modal', '[data-toggle="modal"]', function(e) {
  var $this = $(e.currentTarget);
  $this.data("opening", false);
})


// tab lazy loading
$.fn.tabLazyLoading = function(url) {
  var $tab = $(this);
  $.get(url).done(function(data) {
    $($tab.data('target')).empty().append(data);
    $tab.data('loaded', 'true');
  }).fail(function() {
    if(!$($tab.data('target')).find('.loading-error').length)
    $($tab.data('target')).append('<p class="text-danger loading-error">网络异常，请稍后重新加载...</p>');
  });
}
